entry {
    ui::interact-with-window {
        title: { const 'SSS Editor' },
        content: Root,
        assets: [EditorStyles],
        on-close: { Some { sys::exit 0 } }
    }
};

asset EditorStyles: AssetCSS 'editor.css';

const Root: ui::Component
    \ use
    let color := { ui::State {std2cv {Some Black}} },
    { { ui::Box ['playground'] } [
        { ui::Label 'prototype playground' },
        { edit color }
    ] };

function cv2std:
    &(sss::#ColorValue) => Maybe[Color]
    & { set, h, s, l, a } =>
        if set:
            let h := { Number h },
            let s := (({ Number s } * 255) / 100),
            let l := (({ Number l } * 255) / 100),
            let a := { Number (a ?? 100.0) },
            { Some { Color { h, s, l, a } } },
        else:
            None;

function std2cv:
    &(Maybe[Color]) => sss::#ColorValue
    &(value?) =>
        switch value?:
        case Some value:
            let (h,s,l,a) := value.hsla,
            let h := { !!! { Float h } },
            let s := { !!! { Float ((s * 100) / 255) } },
            let l := { !!! { Float ((l * 100) / 255) } },
            let a := if (a != 100): { Some { !!! { Float a } } }, else: None,
            { |sss::#ColorValue| { set: Yes, h, s, l, a } },
        case None:
            { |sss::#ColorValue| { set: No, h: 0, s: 0, l: 0, a: None } },
        end;

export function edit:
    &(Reactive[sss::#ColorValue]) => ui::Component
    &(color) =>
        let color-text := (
            \ map
            let value := color.out,
            switch {cv2std value}:
            case Some std-value: std-value.css-value,
            case None: 'None',
            end
        ),
        let color-bg := { ui::DynamicInlineStyle
            \ map
            let value := color.out,
            [('background',({cv2std value} ?? White).css-value)]
        },
        let select-by-dialog := { |.[Async]|
            \ await
            let current := color.out.sample,
            let current := ({cv2std current} ?? White),
            \ await
            let value? := {
                ui::modal-get-color
                { title: 'Select Color', initial: current }
            },
            switch value?:
            case Some _: (color.in <- {std2cv value?}),
            case None: Noop,
            end
        },
        { { ui::Box [] } [
            { ui::Text color-text },
            ({ ui::Label '　' } with color-bg),
            { ui::Button ('…', (Noop with select-by-dialog)) }
        ] };
